package com.jdd.common.util;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.RandomStringUtils;

/**
 * 雪花算法工具类
 */
public class SnowFlakeUtil {

    private long machineId ;
    private long dataCenterId ;

    private static final long MACHINE_ID_STATIC = createStaticId();
    private static final long DATA_CENTER_ID_STATIC = createStaticId();

    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil(MACHINE_ID_STATIC,DATA_CENTER_ID_STATIC);
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象
     */
    public static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(0L, 0L);
    }

    private Snowflake snowflake = IdUtil.createSnowflake(machineId,dataCenterId);

    public synchronized String id(){
        return String.valueOf(snowflake.nextId());
    }

    public static String getId() {

        return SnowFlakeUtil.get().id();
    }
    private static Long createStaticId(){
        long id = System.currentTimeMillis();
        String randomId = id + RandomStringUtils.randomNumeric(5);
        id = Long.parseLong(randomId);
        return id;
    }
}
